﻿/*
 * Copyright (C) 2009 Gentea Alexandru <in.10se@yahoo.com>
 * 
 *
 * This file is part of WordNet::SQLConverter
 * See http://wnsqlconverter.codeplex.com/ for details.
 *
 * WordNet::SQLConverter is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * WordNet::SQLConverter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using GDALib;
using NLog;

namespace WordNet.SQLConverter
{
    public enum DbType
    { 
        SqlServer,
        Postgresql,
        Mysql,
        Oracle,
        SQLite
    }

    class DatabaseBuilder
    {
        DatabaseAccessor dbAccessor;
        String scriptsPath;
        static String[] scriptFiles = { "database.sql", "tables.sql", "constraints.sql", "indexes.sql", "table_data.sql" };
        Logger logger;
        bool isRunning;

        public bool IsRunning
        {
            get { return isRunning; }
            set { isRunning = value; }
        }
        

        public DatabaseBuilder(DatabaseAccessor dbAccessor, String scriptsPath)
        {
            this.dbAccessor = dbAccessor;
            this.scriptsPath = scriptsPath;
            this.logger = LogManager.GetCurrentClassLogger();
        }

        public bool BuildDatabase(String dbName, String dbPath, DbType type, BackgroundWorker workerThread, DoWorkEventArgs e)
        {
            StreamReader fileReader = null;
            StringBuilder sqlScript = new StringBuilder(8000);
            String message;

            for (int i = 0; i < scriptFiles.Length; i++)
                try
                {
                    //we stop the operation if we get the cancel signal
                    if (workerThread.CancellationPending)
                    {
                        e.Cancel = true;
                        return false;
                    }

                    //this step represents 5% of the whole process
                    workerThread.ReportProgress(i, "Executing " + scriptFiles[i] + "...");
                    fileReader = new StreamReader(scriptsPath + "/" + type.ToString() + "/" + scriptFiles[i]);

                    //set the database for tables.sql and constraints.sql
                    //if (i > 0)
                    //    sqlScript.Append("USE [" + dbName + "];");
                     
                    //read the script and make some edits
                    sqlScript.Append(fileReader.ReadToEnd());
                    fileReader.Close();
                    sqlScript.Replace("\r\nGO", ";");

                    if(i == 0)
                        sqlScript.Replace("_DB_NAME_", dbName);
        
                    //execute the script
                    if (dbAccessor.ExecuteNonQuery(sqlScript.ToString()) == 0)
                    {
                        logger.Error("Failed to execute script file: " + scriptFiles[i]);
                        return false;
                    }

                    if (i == 0)
                    {
                        dbAccessor.ConnectionString = dbAccessor.ConnectionString.
                            Replace("Initial Catalog=", "Initial Catalog=" + dbName);
                    }

                    sqlScript.Remove(0, sqlScript.Length);
                }
                catch (Exception ex)
                {
                    message = "Failed to open file. Error: " + ex.Message;
                    logger.Error(message);

                    if (fileReader != null)
                        fileReader.Close();

                    return false;
                }

            return true;
        }
    }
}
